include(ExternalProject)

CPMAddPackage(
    NAME ffmpeg
    GIT_REPOSITORY https://gitee.com/ls56647426/ffmpeg.git
    GIT_TAG n4.4
    DOWNLOAD_ONLY YES
)

macro(add_ffmpeg_library target)
    add_library(${target} SHARED IMPORTED)
    if(NOT TARGET ${target})
        message("not target ${target}.")
    endif()
    set_target_properties(${target} PROPERTIES
        IMPORTED_LOCATION_RELEASE ${ffmpeg_SOURCE_DIR}/build/lib/lib${target}.so
        IMPORTED_LOCATION_DEBUG ${ffmpeg_SOURCE_DIR}/build/lib/lib${target}.so
        IMPORTED_IMPLIB_RELEASE ${ffmpeg_SOURCE_DIR}/build/lib/lib${target}.so
        IMPORTED_IMPLIB_DEBUG ${ffmpeg_SOURCE_DIR}/build/lib/lib${target}.so
    )
    execute_process(COMMAND rm -rf
        ${LIBRARY_OUTPUT_PATH}/lib${target}.so
    )
    execute_process(COMMAND ln -s
        ${ffmpeg_SOURCE_DIR}/build/lib/lib${target}.so
        ${LIBRARY_OUTPUT_PATH}/lib${target}.so
    )
endmacro()

# ffmpeg has no CMakeLists, so we create our own target
if(ffmpeg_ADDED)
    if (WIN32)
        # TODO: qt 命令行不支持 ./configure 命令，无法通过正常手段编译这个仓库
        # 考虑准备好 windows 环境依赖库 dll，下载后直接链接
    elseif (APPLE)
    elseif (UNIX)
        ExternalProject_Add(ffmpeg
            SOURCE_DIR ${ffmpeg_SOURCE_DIR}
            LOG_DIR ${ffmpeg_SOURCE_DIR}/log
            BINARY_DIR ${ffmpeg_SOURCE_DIR}/build
            CONFIGURE_COMMAND cd ${ffmpeg_SOURCE_DIR} && ./configure
                --enable-shared
                --prefix=${ffmpeg_SOURCE_DIR}/build
                --disable-x86asm
                --enable-pic
            BUILD_COMMAND cd ${ffmpeg_SOURCE_DIR} && make -j4
            INSTALL_COMMAND cd ${ffmpeg_SOURCE_DIR} && make install
        )
    endif()

    set(FFMPEG_LIBRARYS avcodec avdevice avfilter avformat avutil swresample swscale)

    foreach(library ${FFMPEG_LIBRARYS})
        add_ffmpeg_library(${library})
    endforeach()
endif()
